var TeamLayer = cc.Layer.extend({
    isMouseDown:false,

    ccbNode:null,

    attrDrawingSprite:null,
    floatItem: null,

    init:function () {

        //////////////////////////////
        // 1. super init first
        this._super();
        this.setTouchEnabled(true);
        /////////////////////////////
        // 2. add a menu item with "X" image, which is clicked to quit the program
        //    you may modify it.
        // ask director the window size
        var size = cc.Director.getInstance().getVisibleSize();
        var size2 =  cc.Director.getInstance().getWinSize();

        cc.BuilderReader.setResourcePath("ccb/");

        //load ccbi scene
        this.ccbNode = cc.BuilderReader.load("ccb/TeamScene.ccbi", this);
        //this.ccbNode.animationManager.setCompletedAnimationCallback(this, this.animationCompleteCallback);

        //init scene
        //read record
        /*
            back 2
            confirm 3
            team 20
                box 1-4 
                    character 1
            characters 30
                box 1-25
                    character 1
            attr_node 10
                attr_bg 1
            dragIcon 100
        */
        var attrBgNode=this.ccbNode.getChildByTag(10).getChildByTag(1);
        var attrNodeSize=attrBgNode.getContentSize();
        var attrNodePosition=attrBgNode.getPosition();
        var attrNodeScaleX=attrBgNode.getScaleX();
        var attrNodeScaleY=attrBgNode.getScaleY();
        if(this.attrDrawingSprite==null){
            this.attrDrawingSprite=new AttrDrawingSprite(attrNodeSize.width,attrNodeSize.height);
            this.attrDrawingSprite.setAttribute(8,9,7,6,5,7);
            this.attrDrawingSprite.setPosition(attrNodeSize.width/2,attrNodeSize.height/2);
        }

        this.floatItem=this.ccbNode.getChildByTag(100);
        this.floatItem.setVisible(false);

        if(this.ccbNode != null) {
            this.addChild(this.ccbNode);
        }

        attrBgNode.addChild(this.attrDrawingSprite);

        this.hideAttribute();

        this.initTouchPositions();

        // init team and roles
        this.refreshTeam();
        for(var j=1;j<=25;j++){
            var characterSprite=this.ccbNode.getChildByTag(30).getChildByTag(j).getChildByTag(1);
            if(Game.characterBaseAttrInfo[j]!=null && typeof Game.characterBaseAttrInfo[j]!="undefined"){
                var texture = cc.TextureCache.getInstance().addImage("character/"+j+".png");
                characterSprite.setTexture(texture);
            }else{
                characterSprite.setVisible(false);
            }
        }
    },
    animationCompleteCallback: function(){
        console.log("animation end...");
    },

    backBtnRect:null,
    confirmBtnRect:null,
    teamBorderRect:null,
    teamRects:[],
    availableRects:[],
    rectsInited:false,
    initTouchPositions: function(){
        console.log("init Touch Positions");
        if(!this.rectsInited){
            for(var i=1; i<=4; i++){
                this.teamRects[i]=this.ccbNode.getChildByTag(20).getChildByTag(i).getBoundingBox();
                console.log("team"+i,this.teamRects[i]);
            }
            for(var i=1; i<=25; i++){
                this.availableRects[i]=this.ccbNode.getChildByTag(30).getChildByTag(i).getBoundingBox();
                console.log("character"+i,this.availableRects[i]);
            }
            this.backBtnRect=this.ccbNode.getChildByTag(2).getBoundingBox();
            this.confirmBtnRect=this.ccbNode.getChildByTag(3).getBoundingBox();
            this.teamBorderRect=this.ccbNode.getChildByTag(20).getBoundingBox();

            this.rectsInited=true;
        }
    },
    showAttribute:function(characterId){
        var atk=Game.characterBaseAttrInfo[characterId]["atk"];
        var def=Game.characterBaseAttrInfo[characterId]["def"];
        var spd=Game.characterBaseAttrInfo[characterId]["spd"];
        var vit=Game.characterBaseAttrInfo[characterId]["vit"];
        var skl=Game.characterBaseAttrInfo[characterId]["skl"];
        var pte=Game.characterBaseAttrInfo[characterId]["pte"];
        //atk,def,spd,vit,skl,pte
        this.attrDrawingSprite.setAttribute(atk,def,spd,vit,skl,pte);
    },
    hideAttribute:function(){
        this.attrDrawingSprite.setAttribute(0,0,0,0,0,0);
    },

    touchedTeamOrCharacter:0, // 1 team 2 character  点击的是队伍还是人物
    touchedCharacterId:0, // 1-25 点击的人物位置
    touchedIndex:0, // 1-20 or 1-10 点击的物品index
    onTouchesEnded: function(pTouch, pEvent){
        var touchPoint=pTouch[0].getLocation();
        // console.log("touch end",touchPoint);

        // touch on back
        if(cc.rectContainsPoint(this.backBtnRect, touchPoint)){
            console.log("Touch BACK");
            Game.currScene=new MainStageScene();
            cc.Director.getInstance().replaceScene(cc.TransitionFade.create(0.5, Game.currScene, cc.black()));
            return true;
        }
        // touch on confirm
        if(cc.rectContainsPoint(this.confirmBtnRect, touchPoint)){
            console.log("Touch Confirm");
            Game.currScene=new MainStageScene();
            cc.Director.getInstance().replaceScene(cc.TransitionFade.create(0.5, Game.currScene, cc.black()));
            return true;
        }

        this.floatItem.setVisible(false);

        // touch on team
        if(cc.rectContainsPoint(this.teamBorderRect,touchPoint)){
            if(this.touchedTeamOrCharacter==2){
                Game.teamAddCharacter(Game.currRecord, this.touchedCharacterId);
                this.refreshTeam();
            }

            var pointAtTeam=this.ccbNode.getChildByTag(20).convertToNodeSpace(touchPoint);
            // console.log("converted",pointAtTeam);
            for(var i=1;i<=4;i++){
                if(cc.rectContainsPoint(this.teamRects[i], pointAtTeam)){
                    return true;
                }
            }
        }else{
            if(this.touchedTeamOrCharacter==1){
                Game.teamDelCharacter(Game.currRecord, this.touchedIndex);
                this.refreshTeam();
            }
            // touch on characters
            var pointAtCharacters=this.ccbNode.getChildByTag(30).convertToNodeSpace(touchPoint);
            for(var i=1;i<=25;i++){
                if(cc.rectContainsPoint(this.availableRects[i], pointAtCharacters)){
                    return true;
                }
            }
        }
        this.hideAttribute();
        this.cancelSelectBorder();

        touchedTeamOrCharacter=0;
        touchedCharacterId=0;
        touchedIndex=0;
    },
    onTouchesBegan: function(pTouch, pEvent){
        var touchPoint=pTouch[0].getLocation();

        // touch on team
        var pointAtTeam=this.ccbNode.getChildByTag(20).convertToNodeSpace(touchPoint);
        // console.log("converted",pointAtTeam);
        for(var i=1;i<=4;i++){
            if(cc.rectContainsPoint(this.teamRects[i], pointAtTeam)){
                // console.log("Touch on TEAM CHARACTER"+i);
                if(Game.gameRecord[Game.currRecord]["character"]["0"][i]>0){
                    var characterImgPath="character/"+Game.gameRecord[Game.currRecord]["character"]["0"][i]+".png"
                    var texture = cc.TextureCache.getInstance().addImage(characterImgPath);
                    this.floatItem.setTexture(texture);

                    this.touchedTeamOrCharacter=1; // 1 team 2 character  点击的是队伍还是人物
                    this.touchedCharacterId=Game.gameRecord[Game.currRecord]["character"]["0"][i]; // 1-25 点击的人物位置
                    this.touchedIndex=i; // 1-4 or 1-25 点击位置index

                    this.showAttribute(Game.gameRecord[Game.currRecord]["character"]["0"][i]);
                    this.showSelectBorder(1,i);
                }else{
                    this.hideAttribute();
                    this.cancelSelectBorder();
                }
                return true;
            }
        }
        // touch on characters
        var pointAtCharacters=this.ccbNode.getChildByTag(30).convertToNodeSpace(touchPoint);
        for(var i=1;i<=25;i++){
            if(cc.rectContainsPoint(this.availableRects[i], pointAtCharacters)){
                if(typeof Game.characterBaseAttrInfo[i]!="undefined" && Game.characterBaseAttrInfo[i]!=null){
                    var characterImgPath="character/"+i+".png"
                    var texture = cc.TextureCache.getInstance().addImage(characterImgPath);
                    this.floatItem.setTexture(texture);

                    this.touchedTeamOrCharacter=2; // 1 team 2 character  点击的是队伍还是人物
                    this.touchedCharacterId=i; // 1-25 点击的人物位置
                    this.touchedIndex=i; // 1-4 or 1-25 点击位置index

                    this.showAttribute(i);
                    this.showSelectBorder(2,i);
                }else{
                    this.hideAttribute();
                    this.cancelSelectBorder();
                }
                // console.log("Touch on AVAILABLE CHARACTER"+i);
                return true;
            }
        }
    },
    onTouchesMoved: function(pTouch, pEvent){
        var touchPoint=pTouch[0].getLocation();

        this.floatItem.setVisible(true);
        this.floatItem.setPosition(touchPoint);
    },
    // type:1 team type:2 character
    showSelectBorder: function(type,index){
        if(type==1){
            // 是Team 人物全取消选中
            for(var i=1;i<=25;i++){
                this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setVisible(false);
                this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setOpacity(0);
            }
            for(var i=1;i<=4;i++){
                if(index==i){
                    this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setVisible(true);
                    this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setOpacity(255);
                }else{
                    this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setVisible(false);
                    this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setOpacity(0);
                }
            }
        }
        if(type==2){
            // 是人物 队伍全取消选中
            for(var i=1;i<=4;i++){
                this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setVisible(false);
                this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setOpacity(0);
            }
            for(var i=1;i<=25;i++){
                if(index==i){
                    this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setVisible(true);
                    this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setOpacity(255);
                }else{
                    this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setVisible(false);
                    this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setOpacity(0);
                }
            }
        }
    },
    cancelSelectBorder: function(){
        for(var i=1;i<=25;i++){
            this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setVisible(false);
            this.ccbNode.getChildByTag(30).getChildByTag(i).getChildByTag(2).setOpacity(0);
        }
        for(var i=1;i<=4;i++){
            this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setVisible(false);
            this.ccbNode.getChildByTag(20).getChildByTag(i).getChildByTag(2).setOpacity(0);
        }
        this.hideAttribute();
    },
    refreshTeam:function(){
        for(var j=1;j<=4;j++){
            var characterSprite=this.ccbNode.getChildByTag(20).getChildByTag(j).getChildByTag(1);
            var roleId=Game.gameRecord[Game.currRecord]["character"][0][j];
            if(roleId>0){
                var texture = cc.TextureCache.getInstance().addImage("character/"+roleId+".png");
                characterSprite.setTexture(texture);
                characterSprite.setVisible(true);
            }else{
                characterSprite.setVisible(false);
            }
        }
    }
});

var TeamScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new TeamLayer();
        layer.init();
        this.addChild(layer);
    }
});